import React, { useState } from 'react';
import { history } from 'umi';
import { Form, Input, Button, Alert, message } from 'antd';
import style from './style.module.less';
import { useModel } from '@@/plugin-model/useModel';
import { apiAccountLoginApi, apiGetCurrentInfo } from '@/api/account.api';
import { InitialState } from '@@/plugin-initial-state/exports';
import { useRequest } from 'ahooks';

export default () => {
  const { initialState, setInitialState } = useModel<InitialState>(
    '@@initialState',
  );
  const { run, loading, error } = useRequest(apiAccountLoginApi, {
    manual: true,
    throwOnError: true,
    onSuccess: async res => {
      console.log('res', res)
      if (res.success) {
        message.success('登录成功');

        const { data } = await apiGetCurrentInfo();

        setInitialState({
          ...initialState,
          userinfo: data.info,
          policys: data.policys,
        });

        history.push('/');
      }
    },
  });

  return (
    <div className={style.bg}>
      <div className={style.panel}>
        <div className={style.main}>
          <h3 className={style.title}>{initialState.title}</h3>

          {error && (
            <Alert
              className={style.error}
              message={error}
              type={'error'}
              showIcon
            />
          )}

          <Form
            layout={'vertical'}
            scrollToFirstError
            onFinish={v => run(v as any)}
          >
            <Form.Item
              label="账号"
              name="username"
              rules={[
                {
                  required: true,
                  message: '管理账号必填',
                },
              ]}
            >
              <Input placeholder="输入管理账号" />
            </Form.Item>

            <Form.Item
              label="密码"
              name="password"
              rules={[
                {
                  required: true,
                  message: '请输入登录密码',
                },
              ]}
            >
              <Input
                placeholder="输入登录密码"
                autoComplete={'off'}
                type={'password'}
              />
            </Form.Item>

            <Form.Item>
              <Button
                block={true}
                htmlType={'submit'}
                loading={loading}
                type={'primary'}
              >
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    </div>
  );
};
